<?php

namespace App\Imports;

use App\Models\Flight\FlightInfo;
use App\Models\Flight\Order;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

class DemoImport extends CommonImport
{

    public function __construct(array $params=[]) {
        $this->params = $params;
        $this->instance = new Order();
    }

    private function getCode(){
        $codes =  Order::query()->pluck('code')->toArray();
        $code = generateRandomString();
        while (in_array($code,$codes)){
            $code = generateRandomString();
        }

        return $code;
    }

    /**
    * @param Collection $collection
    */
    public function collection(Collection $collection)
    {
        $this->records = [];
        $this->count = $collection->count();
        $time = date('Y-m-d H:i:s');
        $d = 25569;
        $t = 24 * 60 * 60;
        //Log::info('res',$collection->toArray());
        $mapFlight = FlightInfo::query()->get(['id','date','flight_no']);

        $codes =  Order::query()->pluck('code')->toArray();

        foreach ($collection as $k=>$v) {
            if($k<=0)continue;//过滤表头
            $v = $v->toArray();
            if(count(array_filter($v))<=0){continue;}

            $birthday = date('Y-m-d',(intval($v[3])-25569)*24*3600);
            $date = date('Y-m-d',(intval($v[4])-25569)*24*3600);
            $backDate = date('Y-m-d',(intval($v[6])-25569)*24*3600);


            //如果没有记录编码，就自动生成
            if(empty($v[8])){
                $code = generateRandomString();
                while (in_array($code,$codes)){
                    $code = generateRandomString();
                }
                $codes[] = $code;
                $v[8] = $code;
            }

            Log::error('map',$v);
            Log::error('date',[$date]);
            //dd($v);
            $v[3] = Str::replace('/', '-', $v[3]);
            $v[4] = Str::replace('/', '-', $v[4]);
            $v[6] = Str::replace('/', '-', $v[6]);

            $data = [
                'code'=>strtoupper($v[8]),
                'name'=>$v[0],
                'passport'=>$v[1],
                'passenger_sex'=>$v[2]=='男'?'M':'F',
                'passenger_birthday'=>$birthday,
                'passenger_type'=>getPassagerType($birthday),
                'is_hide'=>0,
                'is_double'=>!empty($v[6]) && !empty($v[7])?1:0,
                'flight_id'=>$mapFlight->where('date',$date)->where('flight_no',$v[5])->first()->id,
                //'couple_flight_id'=>$mapFlight->where('date',date('Y-m-d',(intval($v[6])-25569)*24*3600))->where('flight_no',$v[7])->first()->id??0,
                'couple_flight_id'=>$mapFlight->where('date',$backDate)->where('flight_no',$v[7])->first()->id,
                'beizhu'=>$v[9]??'',
                'created_at'=>$time,
                'updated_at'=>$time,
                'writer_id'=>$this->params['id'],
            ];
            $this->records[] = $data;
            /*$this->records[] = array_merge($data,['flight_id'=>$mapFlight->where('date',$date)->where('flight_no',$v[1])->first()->id]);
            //如果有返程数据,返程日期和返程航班号同时不为空
            if(!empty($v[6]) && !empty($v[7])){
                $goDate = date('Y-m-d',(intval($v[6])-25569)*24*3600);
                $this->records[] = array_merge($data,['flight_id'=>$mapFlight->where('date',$goDate)->where('flight_no',$v[8])->first()->id]);
            }*/

            //$this->countSuccess++;
        }
        try{
            DB::beginTransaction();
            $this->countSuccess = count($this->records);
            $this->instance->insert($this->records);
            DB::commit();
            $this->msg = "本次导入共：".$this->count.'条数据，成功：'.$this->countSuccess.'条，失败：'.$this->countFail.'条';
            return true;
        }catch(\Exception $e){
            DB::rollback();
            $this->success = false;
            $this->msg = $tip = $e->getFile().':'.$e->getLine().':'.$e->getMessage();
            Log::error($tip);
            return false;
        }

    }

}
